<template>
  <div>
  <Swipe></Swipe>
<!--    <van-divider />-->
    <!--    通知栏-->
    <div style="margin-top: -60px;margin-bottom: 10px;">
      <van-notice-bar
        left-icon="volume-o"
        text="无论我们能活多久，我们能够享受的只有无法分割的此刻，此外别无其他。"
      />
    </div>
    <!-- 日历选择组件 -->
    <div class="be-on-duty">
      <div class="calendar mb-10">
        <van-calendar
          :show-title="false"
          ref="calendars"
          :poppable="false"
          :show-confirm="false"
          :default-date="defaultDate"
          :style="{ height: '420px', }"
          :formatter="formatter"
          :min-date="minDate"
          :max-date="maxDate"
          @select="handelSelect"
        >
        </van-calendar>

         <div>
           <van-icon name="arrow-left" @click="arrowLeft" />
           <van-button type="danger" @click="goNow">回今天</van-button>
           <van-icon name="arrow" @click="arrowRight" />
         </div>
      </div>
    </div>
<!--    详情-->
    <div style="margin: 5px">
      <van-row class="info">
        <van-col span="12" class="infoList">阳历: {{ dayjs(info.date).format('YYYY-MM-DD')}}</van-col>
        <van-col span="12" class="infoList">农历: {{info.lunarInfo}}</van-col>
        <van-col span="12" class="infoList" >星座: {{ info.customInfo?.constellation||'--' }}</van-col>
        <van-col span="12" class="infoList">赶场: 赶集 买花 消费</van-col>
      </van-row>
    </div>

<!--    浮动气泡-->
    <van-floating-bubble
      axis="xy"
      icon="chat"
      magnetic="x"
      v-model:offset="state.offset"
    />

  </div>
</template>

<script setup>
import { ref, onMounted,reactive } from 'vue'
import dayjs from 'dayjs'
import calendar  from "js-calendar-converter"
import Swipe from '../../components/Swipe.vue'
import { Calendar, Button, Icon } from "vant"

const calendars = ref(null)
const minDate = ref(new Date())
const maxDate = ref(new Date())
const defaultDate = ref(new Date())
const dutyList = ref([])
const cont = ref(0)
const year = ref(new Date().getFullYear())
const month = ref(new Date().getMonth())
const nowDay = ref(new Date().getDate())
const showYear = ref(new Date().getFullYear())
const showMonth = ref(new Date().getMonth())
const info = ref({})
const state = reactive({
  offset: {x:document.body.clientWidth*286/330,y:750}
})
onMounted(() => {
  _setMinMaxDay()
  handelSelect()
})

// 返回首页
const goHome = () => {
  // Implement home navigation
}

// 回到今天
const goNow = () => {
  defaultDate.value = new Date()
  minDate.value = new Date()
  maxDate.value = new Date()
  cont.value = 0
  _setMinMaxDay()
}

const _setMinMaxDay = () => {
  showYear.value = defaultDate.value.getFullYear()
  showMonth.value = defaultDate.value.getMonth()
  const firstDay = new Date(defaultDate.value)
  firstDay.setDate(1)
  minDate.value = new Date(
    showYear.value,
    showMonth.value,
    firstDay.getDate()
  )
  const endDay = new Date(showYear.value, showMonth.value + 1, 1)
  endDay.setDate(0)
  maxDate.value = new Date(showYear.value, showMonth.value, endDay.getDate())
}

// 设置显示月份可选择的天数区间
const setMinMaxDay = () => {
  const firstDay = new Date(defaultDate.value)
  firstDay.setDate(1)
  minDate.value = new Date(
    year.value,
    month.value + cont.value,
    firstDay.getDate()
  )

  const endDate = new Date(defaultDate.value)
  endDate.setMonth(defaultDate.value.getMonth() + 1)
  endDate.setDate(0)
  maxDate.value = new Date(
    year.value,
    month.value + cont.value,
    endDate.getDate()
  )
}

// 当前月上一个月
const arrowLeft = () => {
  cont.value--
  const days = getMonthDays(year.value, month.value + cont.value)
  defaultDate.value = new Date(
    year.value,
    month.value + cont.value,
    nowDay.value > days ? days : nowDay.value
  )
  _setMinMaxDay()
}

const getMonthDays = (year, month) => {
  let days = new Date(year, month + 1, 0).getDate()
  return days
}

// 当前月下一个月
const arrowRight = () => {
  cont.value++
  const days = getMonthDays(year.value, month.value + cont.value)
  defaultDate.value = new Date(
    year.value,
    month.value + cont.value,
    nowDay.value > days ? days : nowDay.value
  )
  _setMinMaxDay()
}

const getNowDuty = () => {
  // const y = defaultDate.value.getFullYear()
  // const m = defaultDate.value.getMonth() + 1
  // const formattedMonth = m < 10 ? "0" + m : m
  // const obj = {
  //   month: `${y}-${formattedMonth}`,
  // }
  // queryDutySchedule(obj).then((res) => {
  //   dutyList.value = res.data
  // })
}

const formatter = (day) => {
  const _time = new Date(day.date);
  const y = _time.getFullYear();
  const m = _time.getMonth() + 1;
  const d = _time.getDate();
  const w = _time.getDay();
  const info = calendar.solar2lunar(y, m, d); // 确保这个库返回完整数据

  // 1. 改变周六周日显示颜色
  if (w === 0 || w === 6) {
    day.className = "weekendRed";
  }

  // 2. 添加水利日期（假设info中有waterDate字段，或自行计算）
  // 这里需要你有一个水利日期的数据源或计算逻辑
  // 例如：
  // if (isWaterDate(y, m, d)) {
  //   day.waterInfo = "水利";
  // }

  // 3. 农历日期（已存在，但可以优化显示）
  if (info.IDayCn && info.IDayCn !== "初一") {
    day.lunarInfo =`${info.IMonthCn}${info.IDayCn}`; // 单独存放农历日期
  } else if (info.IMonthCn) {
    day.lunarInfo = info.IMonthCn; // 如果是初一，显示月份
  }

  // 4. 星座（根据公历日期计算）
  const constellation = getConstellation(m, d);
  if (constellation) {
    day.constellation = constellation;
  }

  // 5. 忌宜信息（需要额外数据源）
  // 假设你有一个忌宜数据源或API
  // const dailyLucky = getDailyLuckyInfo(y, m, d);
  // if (dailyLucky) {
  //   day.luckyInfo = {
  //    宜: dailyLucky.suitable,
  //    忌: dailyLucky.avoid
  //   };
  // }

  // 6. 节日/节气/农历的显示优先级（保持原有逻辑）
  if (info.festival) {
    day.bottomInfo = info.festival;
  } else if (info.Term) {
    day.bottomInfo = info.Term;
  } else if (info.IDayCn) {
    day.bottomInfo = info.IDayCn;
  }

  // 可选：将额外信息合并到tooltip或自定义渲染
  day.customInfo = {
    lunar: day.lunarInfo,
    constellation: day.constellation,
    // lucky: day.luckyInfo,
    // water: day.waterInfo
  };

  return day;
};

// 辅助函数：根据公历日期计算星座
function getConstellation(month, day) {
  const dates = [
    "120|摩羯座", "120|水瓶座", "219|双鱼座", "321|白羊座",
    "420|金牛座", "521|双子座", "621|巨蟹座", "722|狮子座",
    "823|处女座", "923|天秤座", "1023|天蝎座", "1122|射手座", "1222|摩羯座"
  ];
  const key = `${month}${day < 10 ? '0' + day : day}`;
  const match = dates.find(item => key <= item.split('|')[0]);
  return match ? match.split('|')[1] : null;
}

// 选择事件
const handelSelect = (date) => {

  // 如果你需要农历或节气信息，可以调用 formatter 函数
  const formattedDateInfo = formatter({ date })
info.value = formattedDateInfo
  console.log('Formatted date info:', info.value)
}
</script>

<style scoped lang="less">
::v-deep.be-on-duty {
  background-color: gray;
  //border: 1px solid gray;
  .calendar {
    position: relative;
    .van-button--danger {
      height: 1.475rem;
      padding: 0.3125rem;
      position: absolute;
      top: 0.6rem;
      right: 4rem;
    }

    .van-icon-arrow {
      position: absolute;
      top: 0.6rem;
      right: 1.2rem;
      font-size: 1.3rem;
    }

    .van-icon-arrow-left {
      position: absolute;
      top: 0.6rem;
      left: 1.2rem;
      font-size: 1.3rem;
    }

    .van-calendar {
      position: relative;
      .van-calendar__header {
        .van-calendar__header-subtitle {
          font-size: 1rem;
        }

        .van-calendar__weekdays {
          :nth-child(1),
          :nth-child(7) {
            color: red;
          }
        }
      }
    }

    .van-calendar__body {
      .van-calendar__month {
        .van-calendar__days {
          .van-calendar__day {
            font-size: 1.125rem;

            .van-calendar__top-info {
              padding-right: 0.625rem;
              text-align: right;
            }
          }

          .weekendRed {
            color: red !important;
          }
        }
      }
    }
  }

  .remind {
    li {
      background-color: red;
      display: flex;
      justify-content: space-between;

      .remind-left,
      .remind-right {
        text-align: left;
      }
    }
  }
}
.info{
  border: 1px solid #eee;
  height: 100px;
  margin-top: 10px;
  border-radius: 5px;

  display: flex;
  justify-content: center;
  align-items: center;
  .infoList{
    //border: 1px solid #f00;
   font-size: 12px;
    padding: 0 15px;
  }
}
</style>
